using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;

namespace WindowsApplication3
{
    public class SocketServer
    {
        private TcpListener listener;
        private Thread mainThread;
        private List<ClientThread> childThreads;

        public SocketServer()
        {
            mainThread = new Thread(new ThreadStart(MainThread));
            childThreads = new List<ClientThread>();
            listener = new TcpListener(IPAddress.Any,6969);
        }
        ~SocketServer()
        {
            Abort(); 
        }
        private void AbortChildren()
        {
            foreach (ClientThread T in childThreads)
            {
                T.Abort(); 
            }
        }
        
        private void MainThread()
        {
            try
            {
                listener.Start();  
                while (Thread.CurrentThread.IsAlive)
                {
                    if (listener.Pending())
                    {
                        childThreads.Add(new ClientThread(listener.AcceptSocket()));
                    }
                    Thread.Sleep(500);  
                }
            }
            catch (ThreadAbortException)
            {
                
                EventLog.WriteEntry("RoboSoccer Network Layer", "Network server stopped.", EventLogEntryType.Information);   
            }
            finally
            {
                listener.Stop();  
                AbortChildren();
            } 
        }

        public void Start()
        {
            mainThread.Start();
            EventLog.WriteEntry("RoboSoccer Network Layer", "Network server started.", EventLogEntryType.Information);
        }
        public void Abort()
        {
            mainThread.Abort(); 
        }
       
    }
}
